package com.poster.service.impl;

import com.poster.entity.po.Permission;
import com.poster.enums.PermissionType;
import com.poster.mappers.PermissionMapper;
import com.poster.service.IPermissionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class PermissionService implements IPermissionService {

    private final PermissionMapper permissionMapper;

    public PermissionService(PermissionMapper permissionMapper) {
        this.permissionMapper = permissionMapper;
    }

    // TODO 删除幽灵权限

    /**
     * 将权限枚举映射回数据库
     */
    @Override
    public void restorage() {

        for (PermissionType type : PermissionType.values()) {
            String code = type.getCode();
            try {
                if (permissionMapper.existsByCode(code)) {
                    continue;
                }
                Permission bean = new Permission();
                Permission parent = permissionMapper.selectByCode(type.getPCode());
                if (parent != null) {
                    bean.setPId(parent.getId());
                }
                bean.setCode(code);
                bean.setName(type.getName());
                bean.setIntroduction(type.getIntroduction());
                permissionMapper.insert(bean);
            } catch (DuplicateKeyException e) {
                // （兜底） 为了避免竞争状态，多个实例同时启动导致插入失败则静默跳过
                log.warn("权限 {} 已存在，跳过", code);
            }
        }
    }
}
